🔍 Linear Search vs Binary Search

Help Teju find the target efficiently!

🎯 Problem: Find the Target!

Hi! I'm Teju 👋 I have a sorted array of numbers, and I need to find if a target value exists in it.

There are two ways to search: Linear Search (check one by one) and Binary Search (smart divide & conquer).

📋 Today's Challenge

Input: A sorted array and a target number

Output: "Found at index X" or "Not found"

Goal: Compare how fast each algorithm finds (or doesn't find) the target!

🔎 Linear Search

Linear Search is simple: start from the beginning and check every element one by one until you find the target or reach the end.

How it works:

  1. Start from index 0
  2. Compare current element with target
  3. If match → Found!
  4. If not → Move to next element
  5. Reach end → Not found
3
8
12
17
22
28
35

Currently checking index 1 → Not target → Keep going →

Time Complexity: O(n) → May check all n elements

Best Case: Target at first position → O(1)

Worst Case: Target at end or not present → O(n)

✂️ Binary Search (Divide & Conquer)

Binary Search is super smart! Since the array is sorted, we can eliminate half of the remaining elements in each step!

Algorithm Steps:

  1. Find middle element
  2. If middle == target → Found!
  3. If target < middle → Search left half
  4. If target > middle → Search right half
  5. Repeat until found or no elements left
1
5
8
12
18
25
33
41
50

Middle = 18, Target = 8 → Too high! Eliminate right half

Time Complexity: O(log n) → Halves search space each step!

Best Case: O(1) → Target at middle

Worst Case: O(log n) → Extremely fast even for millions of elements!

🎮 Interactive Demo

Click "Run Search" to begin!

⚔️ Linear vs Binary Search - Head to Head!

Feature Linear Search Binary Search
Time Complexity O(n) O(log n)
Requires Sorted Array? No Yes
Best Case O(1) (first element) O(1) (middle)
Worst Case O(n) O(log n)
Space Complexity O(1) O(1)
Use When... Small/unsorted data Large sorted data

🏆 Winner?

Binary Search wins by a landslide when the array is sorted and large!

For 1 million elements: Linear might take 1 million steps → Binary takes only ~20 steps!